package com.wang.myblog.controller;

import com.alibaba.fastjson.JSONObject;
import com.wang.myblog.common.PageRequest;
import com.wang.myblog.common.PageResponse;
import com.wang.myblog.common.ResponseResult;
import com.wang.myblog.entity.Tag;
import com.wang.myblog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TagController {
    @Autowired
    TagService tagService;

    @RequestMapping("/tagManage")
    public String tagManage(){return "admin/tags";}

    /**
     * 获取标签管理所需的数据
     */
    @PostMapping("/tagInfo")
    @ResponseBody
    public PageResponse tagInfo(@RequestBody PageRequest request){
        request.setSearchMsg(request.getSearchMsg().replace(" ",""));
        if (request.getSearchMsg()=="")
            request.setSearchMsg(null);
        PageResponse pageResponse=tagService.queryByPageAndSearchMsg(request.getDraw(), request.getOffset(), request.getPageSize(), request.getSearchMsg());
        return pageResponse;
    }

    @RequestMapping("/createTag")
    @ResponseBody
    public String createTag(@RequestBody Tag tag){
        ResponseResult result=new ResponseResult();
        if(tagService.queryByName(tag.getName())!=null){
            result.setCode(500);
            result.setData(false);
            result.setMessage("标签名已经存在");
        }else {
            tagService.insert(tag);
            result.setCode(200);
        }
        return JSONObject.toJSONString(result);
    }

    /**
     * 前往编辑标签界面
     */
    @RequestMapping("/editTag")
    public String editTag(Model model,Integer tagId){
        Tag tag=tagService.queryById(tagId);
        model.addAttribute("tag",tag);
        return "admin/editTag";
    }

    /**
     * 编辑标签
     */
    @RequestMapping("/doEditTag")
    @ResponseBody
    public String doEditTag(@RequestBody Tag tag){
        ResponseResult result=new ResponseResult();
        if(tagService.update(tag)){
            result.setCode(200);
        }else {
            result.setCode(500);
            result.setMessage("错误");
        }
        return JSONObject.toJSONString(result);
    }

    /**
     * 删除标签，关联的文章标签置空
     */
    @RequestMapping("/deleteTag")
    @ResponseBody
    public String deleteTag(Integer tagId){
        ResponseResult result=new ResponseResult();
        if(tagService.deleteById(tagId)){
            result.setCode(200);
        }else {
            result.setCode(500);
            result.setMessage("删除失败");
        }
        return JSONObject.toJSONString(result);
    }

}
